package org.martin.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/** 
 * 其实docx属于zip的一种，这里只需要操作word/document.xml中的数据，其他的数据不用动 
 * @author martin
 * 
 */
public class DocxHandle {

  /** 
   *  
   * @param documentFile  动态生成数据的docunment.xml文件 
   * @param docxTemplate  docx的模板 
   * @param toFileName    需要导出的文件路径 
   * @throws ZipException 
   * @throws IOException 
   */

  public void outDocx(File documentFile, File docxTemplate, OutputStream outputStream) throws ZipException, IOException {
    InputStream in = null;
    ZipFile zipFile = null;
    ZipOutputStream zipout = null;
    try {
      zipFile = new ZipFile(docxTemplate);
      Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
      zipout = new ZipOutputStream(outputStream);
      int len = -1;
      byte[] buffer = new byte[1024];
      while (zipEntrys.hasMoreElements()) {
        ZipEntry next = zipEntrys.nextElement();
        //把输入流的文件传到输出流中 如果是word/document.xml由动态生成数据的docunment.xml文件替换
        zipout.putNextEntry(new ZipEntry(next.toString()));
        if ("word/document.xml".equals(next.toString())) {
          try {
            in = new FileInputStream(documentFile);
            while ((len = in.read(buffer)) != -1) {
              zipout.write(buffer, 0, len);
            }
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            if (in != null) {
              in.close();
            }
          }
        } else {
          try {
            in = zipFile.getInputStream(next);
            while ((len = in.read(buffer)) != -1) {
              zipout.write(buffer, 0, len);
            }
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            if (in != null) {
              in.close();
            }
          }
        }
      }
      zipout.flush();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (in != null) {
        in.close();
      }
      if (zipFile != null) {
        zipFile.close();
      }
      if (zipout != null) {
        zipout.close();
      }
      if(outputStream!=null) {
        outputStream.close();
      }
      documentFile.deleteOnExit();
    }
  }
}
